#include "OpenglAppFramework/inc/PlugIn/ActionsPlugIn.h"
#include "OpenglAppFramework/inc/GameObject.h"
#include "OpenglAppFramework/inc/Scene.h"
#include <dlfcn.h>

#include <iostream>

ActionsPlugIn::ActionsPlugIn(const std::string& name) :
    PlugIn(name, PlugInType::Actions) {
    m_actions = nullptr;
}

ActionsPlugIn::~ActionsPlugIn() {}

int ActionsPlugIn::setConfigData(const nlohmann::json&) {
    return 0;
}

int ActionsPlugIn::init() {
    std::string func_name = "get_" + m_obj->name() + "_actions";
    OpenglEnv& env = m_obj->scene()->env();
    GetActionsFunction func = reinterpret_cast<GetActionsFunction>(dlsym(env.dll_handler, func_name.c_str()));
    if(func == nullptr) {
        std::cout << "get symbol failed: " << func_name << std::endl;
        std::cout << dlerror() << std::endl;
        return -1;
    }
    m_actions = func();
    if(m_actions == nullptr) {
        std::cout << "create actions failed: " << func_name << std::endl;
        return -1;
    }
    return 0;
}

void ActionsPlugIn::destroy() {
    if(m_actions != nullptr) {
        delete m_actions;
    }
}

void ActionsPlugIn::routine() {
    m_actions->routine(m_obj);
}
